﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Sector7.Framework.Core;
using Sector7.Medical.EntityType;
using Sector7.Medical.Biz;
using Sector7.Medical.Consts;
using Sector7.Medical.Utility;
using Sector7.Framework.Utility;
using Sector7.Framework.Enums;
using Sector7.Framework.Drivers.RF;
using Microsoft.Win32;
using System.IO;
using Sector7.Framework.Consts;

namespace Sector7.Medical.Windows
{
    /// <summary>
    /// AddPatientWindow.xaml 的交互逻辑
    /// </summary>
    public partial class AddPatientWindow : AddModeWindowBase
    {
        #region ============================================== Main functions

        /// <summary>
        /// 点击浏览按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            var dialog = ClientUtil.CreateOpenFileDialog("选择用户照片", "图片文件（*.png；*.jpg；*.gif；*.bmp）|(*.png;*.jpg;*.gif;*.bmp)");
            var dialogResult = dialog.ShowDialog();

            if (dialogResult == true)
            {
                string filePath = dialog.FileName;
                var result = Agent_TRAS.UploadProfile(m_patient.CitizenId, filePath);
                if (result.ErrorCode == C_ErrorCode.ERR_SYS_SUCCESS)
                {
                    string userDir = PathUtil.GenerateAbsPath(C_PathName.DIR_USER_DATA, m_patient.CitizenId);
                    PathUtil.CheckExists(userDir);

                    string destFilePath = PathUtil.CombinePath(userDir, C_PathName.FILE_AVATAR);
                    File.Copy(filePath, destFilePath, true);

                    imgProfile.Source = new BitmapImage(new Uri(destFilePath));
                }
                else
                {
                    Alert.ShowDialog(AlertType.Error, result.ErrorMessage);
                }
            }
        }

        /// <summary>
        /// 点击重置照片按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, RoutedEventArgs e)
        {
            imgProfile.Source = InterfaceUtil.GetDefaultAvatar();
        }

        #endregion

        #region ============================================== Structure
        public AddPatientWindow()
        {
            InitializeComponent();
        }
        #endregion

        #region ============================================== Accessor

        /// <summary>
        /// 获取病人个人唯一编码
        /// </summary>
        public string CitizenId
        {
            get { return m_patient.CitizenId; }
        }

        #endregion

        #region ============================================== Private functions

        /// <summary>
        /// 为添加功能初始化窗口
        /// </summary>
        protected override void InitializeForCreating()
        {
            m_patient = new M7_Patient();
            m_patient.CitizenId = Guid.NewGuid().ToString("N").ToUpper();

            string date = DateTime.Now.ToString("yyMMdd");

            int seed = Agent_SYSS.GetBinarySeed(
                C_M7_TableName.PATIENT,
                Menvironments.AdministrativeCode);
            txbId.Text = PrimaryKeyUtil.GetPrimaryKey(C_M7_TableName.PATIENT,
                Menvironments.AdministrativeCode,
                date,
                seed).ToString();
            imgProfile.Source = InterfaceUtil.GetDefaultAvatar();

            base.InitializeForCreating();
        }

        /// <summary>
        /// 未其他功能初始化窗口
        /// </summary>
        protected override void InitializeForOthers()
        {
            if (cbbGender.Items == null || cbbGender.Items.Count == 0)
            {
                var genderList = Agent_INFS.GetGenderList();
                ClientUtil.LoadItemsSource(cbbGender, genderList);
            }

            if (cbbIdentityType.Items == null || cbbIdentityType.Items.Count == 0)
            {
                var idTypeList = Agent_INFS.GetIdentityTypeList();
                ClientUtil.LoadItemsSource(cbbIdentityType, idTypeList);
            }

            base.InitializeForOthers();
        }

        /// <summary>
        /// 检查有效性
        /// </summary>
        /// <returns></returns>
        protected override bool CheckData()
        {
            m_errors.Clear();

            m_patient.HealthCardId = RfReaderUtil.GetSerialNumber();
            if (!string.IsNullOrWhiteSpace(m_patient.HealthCardId))
            {
                lblCardNo.Content = m_patient.HealthCardId;

                m_patient.PatientId = Convert.ToInt64(txbId.Text);
                if (RfReaderUtil.WriteData(m_patient.PatientId.ToString()) == RfReader_ErrorCode.ERR_RF_SUCCESS)
                {
                    m_patient.FullName = txbName.Text;
                    m_patient.GenderId = cbbGender.SelectedValue.ToString();
                    m_patient.IdentityTypeId = cbbIdentityType.SelectedValue.ToString();
                    m_patient.IdentityId = txbIdentityId.Text;
                    m_patient.Mobilephone = txbMobilePhone.Text;
                    m_patient.Telephone = txbTelephone.Text;
                    m_patient.PermanetAddr = txbPermanetAddr.Text;
                    m_patient.CurrentAddr = txbCurrentAddr.Text;

                    if (string.IsNullOrWhiteSpace(m_patient.FullName))
                    {
                        m_errors.Add("病人姓名", "不能为空！");
                    }
                    if (string.IsNullOrWhiteSpace(m_patient.GenderId))
                    {
                        m_errors.Add("病人性别", "不能为空！");
                    }
                    if (dtpBirthday.SelectedDate == null)
                    {
                        m_errors.Add("出生日期", "不能为空！");
                    }
                    else
                    {
                        m_patient.Birthday = (DateTime)dtpBirthday.SelectedDate;
                    }
                    if (string.IsNullOrWhiteSpace(m_patient.IdentityTypeId))
                    {
                        m_errors.Add("证件类型", "不能为空！");
                    }
                    if (string.IsNullOrWhiteSpace(m_patient.IdentityId))
                    {
                        m_errors.Add("证件号码", "不能为空！");
                    }
                    if (string.IsNullOrWhiteSpace(m_patient.Mobilephone) && string.IsNullOrWhiteSpace(m_patient.Telephone))
                    {
                        m_errors.Add("移动电话或固定电话", "必须选填一项！");
                    }
                    if (string.IsNullOrWhiteSpace(m_patient.PermanetAddr))
                    {
                        m_errors.Add("户籍地址", "不能为空！");
                    }
                    if (string.IsNullOrWhiteSpace(m_patient.CurrentAddr))
                    {
                        m_errors.Add("居住地址", "不能为空！");
                    }

                    return base.CheckData();
                }
            }

            return false;
        }

        /// <summary>
        /// 执行添加记录功能
        /// </summary>
        protected override void AddData()
        {
            int result = Agent_BIZS.AddPatient(m_patient);
            if (result == C_ErrorCode.ERR_DB_SUCCESS)
            {
                m_isAddSuccess = true;

                Alert.ShowDialog(AlertType.Notification, "添加病人信息成功！");
                base.AddData();
            }
            else
            {
                m_isAddSuccess = false;

                Alert.ShowDialog(AlertType.Error, "添加病人信息失败！");
            }
        }
        #endregion

        #region ============================================== Inner members
        /// <summary>
        /// 窗口关联病人信息
        /// </summary>
        private M7_Patient m_patient = null;
        #endregion
    }
}
